package com.pyz.thread.version.threadlocal;

import com.pyz.thread.entity.Ticket;

import java.util.List;

/**
 * @author yinzhenpu
 * @date 2022/6/4 14:08:15
 * @description 抢票器
 */
public class TicketGrabber implements Runnable {

    private final List<Ticket> tickets;

    private final ThreadLocal<List<Ticket>> threadLocal;

    public TicketGrabber(List<Ticket> tickets, ThreadLocal<List<Ticket>> threadLocal) {
        this.tickets = tickets;
        this.threadLocal = threadLocal;
    }

    public void run() {
        while (tickets.size() > 0) {
            //锁对象不能是this；不同的线程抢的应该是同一把锁；使用this，不同的线程抢的是不同的锁；会导致共享资源的消耗出现不一致；
            synchronized (Ticket.class) {
                //双重校验避免数组越界异常
                if (tickets.size() > 0) {
                    try {
                        Ticket ticket = tickets.get(tickets.size() - 1);
                        threadLocal.get().add(ticket);
                        System.out.println(Thread.currentThread().getName() + " get ticket:" + ticket);
                        tickets.remove(ticket);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        }
        System.out.println(Thread.currentThread() + "一共抢到：" + threadLocal.get().size());
    }
}
